import Cookies from 'js-cookie'
import Http from '@/http'
import API from '@/api'
import Util from '@/utils/common'

const app = {
  state: {
    user:'',
	company:{},
    msgTips:{},
    token: Cookies.get("auth_token"),
    basedata:'',
    sidebar: {
      opened: !+Cookies.get('sidebarStatus')
    },
    language: Cookies.get('language') || 'en'
  },
  mutations: {
    TOGGLE_SIDEBAR: state => {
      if (state.sidebar.opened) {
        Cookies.set('sidebarStatus', 1)
      } else {
        Cookies.set('sidebarStatus', 0)
      }
      state.sidebar.opened = !state.sidebar.opened
    },
    SET_LANGUAGE: (state, language) => {
      state.language = language
      Cookies.set('language', language)
    },
    SET_USER:(state, user) => {
      state.user = user
    },
    SET_COMPANY:(state, company) => {
        state.company = company
    },
    SET_MSGTIPS:(state, msgTips) => {
      state.msgTips = msgTips
    },
    SET_TOKEN:(state, token) => {
      state.token = token
      Cookies.set('auth_token', token)
    },
    SET_BASEDATA(state, basedata) {
      basedata.empty_flag= false
      state.basedata = basedata
    },


  },
  actions: {
    toggleSideBar({ commit }) {
      commit('TOGGLE_SIDEBAR')
    },
    setLanguage({ commit }, language) {
      commit('SET_LANGUAGE', language)
    },
    logOut({ commit, state }) {
      return new Promise((resolve, reject) => {
        commit('SET_TOKEN', '')
        Cookies.set('auth_token', '')
        commit('SET_USER', null)
        resolve()
      })
    },

    initBasedata({state, commit, dispatch}) {
      var obj = Http.syncRequest(API.get_basedata,{});
      if(obj.code==0){
        commit('SET_BASEDATA', obj.data);
      }
    }
  }
}

export default app
